import csv
import json
import re
import numpy as np
import matplotlib.pyplot as plt
import glob


parsed_objects = []
sub_string_pattern = r"\d{1,2}[A-Z]{3}\d{4}\s\d{2}:\d{2}:\d{2}\.\d{3}"

root_path = 'data/3.normal aspirate sample/Sample aspirate/pressure data-6#/ued/200ul/Pressure_2024-02-18_10833_-1_-1.csv'

def count_csv_rows(file_path):
    with open(file_path, newline='') as csvfile:
        csv_reader = csv.reader(csvfile)
        row_count = sum(1 for row in csv_reader)
    return row_count

csv_files = glob.glob(root_path)

for path in csv_files:
    line_indices = list(range(0, count_csv_rows(path)+1, 1))
    # 打开 CSV 文件
    with open(path, newline='') as csvfile:
        # 创建一个 CSV 读取器对象
        csv_reader = csv.reader(csvfile)
        # 逐行读取 CSV 文件内容并打印出来
        for i, row in enumerate(csv_reader):
            if i in line_indices:
                result = ",".join(row)
                match = re.search(sub_string_pattern, result)
                try:
                    start_index = match.start()
                    end_index = match.end()
                except AttributeError:
                    print(path)
                    break
                modified_result = result[:start_index-1] + '0' + result[end_index+1:]
                fixed_json_str = re.sub(r'(?<!["\w])(\w+)(?=:)', r'"\1"', modified_result)
                jdata = json.loads(fixed_json_str)
                parsed_objects = jdata["Pressure_readings"]
                x = np.linspace(0, len(parsed_objects), len(parsed_objects))
                index = [point for point, value in enumerate(parsed_objects) if value > 3500]
                print (index)
                try:
                    sub_list = parsed_objects[index[2]+1:index[3]]
                except IndexError:
                    if jdata["Pump_acceleration_steps"] == 0:
                        print ("EE: Invalid")
                    else:
                        print("EE: Index")
                    continue
                sub_x = np.linspace(0, len(sub_list), len(sub_list))
                diff_data = np.diff(sub_list)
                diff_x = np.linspace(0, len(diff_data), len(diff_data))
                fig, (ax0, ax1, ax2) = plt.subplots(3, 1)

                ax0.plot(x,parsed_objects)
                ax0.grid(True)

                ax1.plot(sub_x,sub_list)
                ax1.grid(True)

                ax2.plot(diff_x, diff_data)
                ax2.grid(True)

                # 调整子图之间的间距
                plt.tight_layout()
                plt.savefig(path[:-4]+str(i)+'.png')
                # 显示图形
                # plt.show()
                plt.close()

# print(sub_list)


